package org.example.config;



import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.dto.base.Result;
import org.example.enums.ResultCodeEnum;
import org.example.util.IpUtils;
import org.example.util.ValidationUtil;
import org.example.util.exception.AppException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 全局异常处理配置
 * 
 */
@Slf4j
@ResponseBody
@ControllerAdvice
public class ExceptionConfig {

	/**
	 * 捕获参数异常
	 * 
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public Result handleBindException(MethodArgumentNotValidException ex) {
		FieldError fieldError = ex.getBindingResult().getFieldError();

		if (fieldError.getDefaultMessage().contains(ValidationUtil.CONVERT_FAILED)) {
			return new Result(false, ResultCodeEnum.EXCEPTION.getId(),fieldError.getField() + "参数类型错误");
		}
		log.info("参数校验失败:{}({})", fieldError.getDefaultMessage(), fieldError.getField());
		return new Result(false,ResultCodeEnum.EXCEPTION.getId(),fieldError.getDefaultMessage());
	}

	/**
	 * 捕获必填参数异常
	 *
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(value = BindException.class)
	public Result handleBindException(BindException ex) {
		FieldError fieldError = ex.getBindingResult().getFieldError();

		if (fieldError.getDefaultMessage().contains(ValidationUtil.CONVERT_FAILED)) {
			return new Result(false,ResultCodeEnum.EXCEPTION.getId(),fieldError.getField() + "参数类型错误");
		}
		log.info("必填校验失败:{}({})", fieldError.getDefaultMessage(), fieldError.getField());

		return new Result(false,ResultCodeEnum.EXCEPTION.getId(),fieldError.getDefaultMessage());

	}

	/**
	 * 全局捕捉异常情况，避免直接报错给前台
	 * 
	 * @param request
	 * @param exception
	 * @return
	 */
	@ExceptionHandler(value = Exception.class)
	public Object exceptionHandler(HttpServletRequest request, Exception exception) {
		log.error("接口路径：{},ip地址：{}, 系统异常:", request.getRequestURI(), IpUtils.getRealIp(request), exception);
		if (exception instanceof AppException) {
			return new Result(false,ResultCodeEnum.EXCEPTION.getId(),exception.getMessage());
		}
		return new Result(false,ResultCodeEnum.EXCEPTION.getId(),"系统功能维护中，请稍后重试");
	}
}
